package com.heer.gymnasium.activity;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.google.gson.Gson;
import com.heer.api.ResponseData.ApiResponse;
import com.heer.api.callback.BaseCallback;
import com.heer.api.constants.StaticValue;
import com.heer.gymnasium.R;
import com.heer.gymnasium.constant.Extras;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.event.BaseEvent;
import com.heer.gymnasium.util.MyImageGetter;
import com.heer.model.BookOrderBean;
import com.heer.model.CreateOrderBean;
import com.heer.model.SidMoneyBean;
import com.heer.model.SiteTicketInfoBean;
import com.heer.model.WxPayBean;
import com.heer.gymnasium.util.PayUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import me.shihao.library.XRadioGroup;
import retrofit2.Call;
import retrofit2.Response;

import static com.heer.gymnasium.event.EventConstant.CREATE_ORDER;
import static com.heer.gymnasium.event.EventConstant.MINE_TO_ORDER;

/**
 * Created by heer on 17/4/7.
 */

public class SiteReservedInfoActivity extends BaseActivity {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_description)
    TextView tvDescription;
    @BindView(R.id.tv_description_info)
    TextView tvDescriptionInfo;
    @BindView(R.id.cbx_notice)
    CheckBox cbxNotice;
    @BindView(R.id.radio_type1)
    RadioButton radioType1;
    @BindView(R.id.tv_pay_type1)
    TextView tvPayType1;
    @BindView(R.id.radio_type2)
    RadioButton radioType2;
    @BindView(R.id.tv_pay_type2)
    TextView tvPayType2;
    @BindView(R.id.radio_type3)
    RadioButton radioType3;
    @BindView(R.id.tv_pay_type3)
    TextView tvPayType3;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.btn_pay)
    TextView btnPay;
    @BindView(R.id.radio_group)
    XRadioGroup radioGroup;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_time_detail)
    TextView tvTimeDetail;
    @BindView(R.id.tv_site_num)
    TextView tvSiteNum;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.layout_book_time)
    LinearLayout layoutBookTime;
    @BindView(R.id.layout_times)
    LinearLayout layoutTimes;
    @BindView(R.id.layout_time)
    LinearLayout layoutTime;
    @BindView(R.id.btn_time_more)
    ImageView btnTimeMore;
    @BindView(R.id.lin_notice_row)
    LinearLayout lin_notice_row;

    private SiteTicketInfoBean mData;
    private PayUtils payUtils;
    private String tid;
    private SVProgressHUD svProgressHUD;

    public static void toReservedInfo(Context context, String t_id, String price) {
        Intent intent = new Intent();
        intent.setClass(context, SiteReservedInfoActivity.class);
        intent.putExtra(Extras.EXTRA_ID, t_id);
        intent.putExtra(Extras.EXTRA_DATA, price);
        context.startActivity(intent);
    }

    public static void toReservedInfo(Context context, String t_id, Serializable times,String isauto) {
        Intent intent = new Intent();
        intent.setClass(context, SiteReservedInfoActivity.class);
        intent.putExtra(Extras.EXTRA_ID, t_id);
        intent.putExtra(Extras.EXTRA_TIME, times);
        intent.putExtra("isauto", isauto);
        context.startActivity(intent);
    }

    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_site_reserved_info);
        payUtils = new PayUtils(this);
    }

    @Override
    protected void initView() {
        super.initView();
        cbxNotice.setChecked(true);
        svProgressHUD=new SVProgressHUD(mContext);
        cbxNotice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //if (isChecked)
                //Toast.makeText(mContext, "选中", Toast.LENGTH_SHORT).show();
                //else
                //Toast.makeText(mContext, "未选中", Toast.LENGTH_SHORT).show();
            }
        });
        //绑定一个匿名监听器
        radioGroup.setOnCheckedChangeListener(new XRadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(XRadioGroup xRadioGroup, @IdRes int i) {
                //获取变更后的选中项的ID
                switch (i) {
                    case R.id.radio_type1:
                        break;
                    case R.id.radio_type2:
                        break;
                    case R.id.radio_type3:
                        break;
                }
            }
        });
        if (getIntent().hasExtra(Extras.EXTRA_TIME)) {
            titleBuilder.setTitleText("订场信息");
            List<BookOrderBean> list = (List<BookOrderBean>) getIntent().getSerializableExtra(Extras.EXTRA_TIME);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd E");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

            if (list.size() > 0) {
                BookOrderBean item = list.get(0);
                tid = item.getTid();
                try {
                    tvTime.setText(sdf.format(sdf2.parse(item.getDay())));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                tvSiteNum.setText(item.getSite_name());
                tvTimeDetail.setText(item.getBegin() + "-" + item.getEnd());
                tvPrice.setText("￥" + item.getPrice());
                long total = 0l;
                for (BookOrderBean it : list) {
                    total += (long) (Double.parseDouble(it.getPrice()) * 100);
                }
                tvTotal.setText("￥" + total / 100d);
            }

            for (BookOrderBean item : list) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.item_reserved_info_times, null);
                TextView time = (TextView) view.findViewById(R.id.tv_time);
                TextView timeDetails = (TextView) view.findViewById(R.id.tv_time_detail);
                TextView siteNum = (TextView) view.findViewById(R.id.tv_site_num);
                TextView price = (TextView) view.findViewById(R.id.tv_price);

                try {
                    time.setText(sdf.format(sdf2.parse(item.getDay())));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                siteNum.setText(item.getSite_name());
                timeDetails.setText(item.getBegin() + "-" + item.getEnd());
                price.setText("￥" + item.getPrice());

                layoutTimes.addView(view);
            }

        } else {
            titleBuilder.setTitleText("购票信息");
            tid = getIntent().getStringExtra(Extras.EXTRA_ID);
        }
    }

    @Override
    protected void loadData() {
        mAppHelper.apiService().getSiteTicketInfo(tid).enqueue(new BaseCallback<ApiResponse<SiteTicketInfoBean>>() {
            @Override
            public void onResponse(Call<ApiResponse<SiteTicketInfoBean>> call, Response<ApiResponse<SiteTicketInfoBean>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful() && response.body().isSccessful()) {
                    mData = response.body().getData();
                    if (mData == null)
                        return;
                    switch (mData.getCat_id()) {
                        case Type.SITE_TICKET_TYPE_1://1:门票
                        case Type.SITE_TICKET_TYPE_2://2:次卡
                        case Type.SITE_TICKET_TYPE_3://3:期卡
                            layoutBookTime.setVisibility(View.GONE);
                            btnTimeMore.setVisibility(View.INVISIBLE);
                            tvTotal.setText("￥" + mData.getPrice_now());
                            break;
                        case Type.SITE_TICKET_TYPE_4://4:包场
                            layoutBookTime.setVisibility(View.VISIBLE);
                            btnTimeMore.setVisibility(View.VISIBLE);
                            break;
                    }
                    tvName.setText(mData.getTicket_name());
                    tvDescription.setText("购票须知:" + mData.getRemark());
                    tvDescriptionInfo.setText(Html.fromHtml(mData.getInfo(), new MyImageGetter(mContext, tvDescriptionInfo), null));

                    mAppHelper.apiService().getSidMoney(mData.getSid()).enqueue(new BaseCallback<ApiResponse<SidMoneyBean>>() {
                        @Override
                        public void onResponse(Call<ApiResponse<SidMoneyBean>> call, Response<ApiResponse<SidMoneyBean>> response) {
                            super.onResponse(call, response);
                            if (response.isSuccessful() && response.body().isSccessful()&&response.body().getData().getMoney()!=null) {
                                try{
                                    tvPayType3.setText("余额支付 余额:￥"+response.body().getData().getMoney());
                                    double money = Double.parseDouble(response.body().getData().getMoney());
                                    double total = Double.parseDouble(tvTotal.getText().toString().replace("￥",""));
                                    if(money>=total) {
                                        radioType3.setChecked(true);
                                    }
                                } catch(Exception e){
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                }
                if(response.body().isTokenExpire()){
                    toLogin();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<SiteTicketInfoBean>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
    }

    @OnClick({R.id.btn_time_more, R.id.btn_pay, R.id.lin_notice_row, R.id.tv_pay_type1, R.id.tv_pay_type2, R.id.tv_pay_type3})
    public void onClick(final View view) {
        switch (view.getId()) {
            case R.id.tv_pay_type1:
                radioType1.setChecked(true);
                break;
            case R.id.tv_pay_type2:
                radioType2.setChecked(true);
                break;
            case R.id.tv_pay_type3:
                radioType3.setChecked(true);
                break;
            case R.id.lin_notice_row:
                if (cbxNotice.isChecked()) {
                    cbxNotice.setChecked(false);
                } else {
                    cbxNotice.setChecked(true);
                }
                break;
            case R.id.btn_time_more:
                if (layoutTimes.getVisibility() == View.VISIBLE) {
                    layoutTimes.setVisibility(View.GONE);
                    layoutTime.setVisibility(View.VISIBLE);
                    btnTimeMore.setImageResource(R.mipmap.arrow_down);
                } else {
                    layoutTimes.setVisibility(View.VISIBLE);
                    layoutTime.setVisibility(View.GONE);
                    btnTimeMore.setImageResource(R.mipmap.arrow_top);
                }
                break;
            case R.id.btn_pay:
                StaticValue.PayType=0;
                if (cbxNotice.isChecked()) {
                    final String payWay;
                    svProgressHUD.showWithStatus("加载中", SVProgressHUD.SVProgressHUDMaskType.BlackCancel);
                    switch (radioGroup.getCheckedRadioButtonId()) {
                        case R.id.radio_type1:
                            payWay = "ali";
                            break;
                        case R.id.radio_type2:
                            payWay = "wx";
                            break;
                        case R.id.radio_type3:
                            payWay = "bal";
                            break;
                        default:
                            payWay = "bal";
                            break;
                    }
                    Toast.makeText(mContext, "提交", Toast.LENGTH_SHORT).show();
                    String times = "";
                    String t_id = getIntent().getStringExtra(Extras.EXTRA_ID);
                    if (getIntent().hasExtra(Extras.EXTRA_TIME)) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        List<BookOrderBean> list = (List<BookOrderBean>) getIntent().getSerializableExtra(Extras.EXTRA_TIME);
                        for (int i = 0; i < list.size(); i++) {
                            if (i > 0)
                                times += ",";
                            else
                                t_id = list.get(0).getTid();
                            try {
                                long begin = sdf.parse(list.get(i).getDay() + " " + list.get(i).getBegin()).getTime() / 1000;
                                long end = sdf.parse(list.get(i).getDay() + " " + list.get(i).getEnd()).getTime() / 1000;
                                times += begin + ":" + end + ":" + list.get(i).getTid();
                            } catch (ParseException e) {
                                new SVProgressHUD(mContext).showErrorWithStatus("时间格式不正确");
                                e.printStackTrace();
                                return;
                            }
                        }
                    }
                    try {
                        mAppHelper.apiService().createOrder(t_id, payWay, getIntent().hasExtra(Extras.EXTRA_TIME) ? times : null,
                                getIntent().getStringExtra("isauto")).enqueue(new BaseCallback<ApiResponse<CreateOrderBean>>() {
                            @Override
                            public void onResponse(Call<ApiResponse<CreateOrderBean>> call, Response<ApiResponse<CreateOrderBean>> response) {
                                super.onResponse(call, response);
                                svProgressHUD.dismiss();
                                if (response.body() != null && !response.body().isSccessful()) {
                                    new SVProgressHUD(mContext).showErrorWithStatus(response.body().getMsg());
                                    return;
                                }
                                StaticValue.payOrderid=response.body().getData().getOrder().getOrder_sn();
                                switch (radioGroup.getCheckedRadioButtonId()) {
                                    case R.id.radio_type1:
                                        //                            payUtils.pay(view, Long.parseLong(getIntent().getStringExtra(Extras.EXTRA_DATA)));

                                        payUtils.pay(view, response.body().getData().getOrder().getPay_money(), response.body().getData().getOrder().getOrder_sn());
                                        break;
                                    case R.id.radio_type2:
                                        mAppHelper.apiService().getWxData(response.body().getData().getOrder().getOrder_sn()).enqueue(new BaseCallback<ApiResponse<WxPayBean>>() {
                                            @Override
                                            public void onResponse(Call<ApiResponse<WxPayBean>> call, Response<ApiResponse<WxPayBean>> response) {
                                                super.onResponse(call, response);
                                                if (response.isSuccessful() && response.body().isSccessful()) {
                                                    WxPayBean data = response.body().getData();
                                                    Gson gson = new Gson();
                                                    String json = gson.toJson(data);
                                                    payUtils.payWx(json);
                                                } else {
                                                    Log.e("PAY_GET", "返回错误" + response.message());
                                                }
                                            }

                                            @Override
                                            public void onFailure(Call<ApiResponse<WxPayBean>> call, Throwable t) {
                                                super.onFailure(call, t);
                                            }
                                        });
                                        break;
                                    case R.id.radio_type3:
                                        Toast.makeText(SiteReservedInfoActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                                        PaySucceedActivity.StartPaySucceed(SiteReservedInfoActivity.this);
                                        finish();
                                        break;
                                    default:
                                        break;
                                }
                            }

                            @Override
                            public void onFailure(Call<ApiResponse<CreateOrderBean>> call, Throwable t) {
                                super.onFailure(call, t);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    Toast.makeText(mContext, "请确认购票须知", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
